package sk.naive.talker.tcpadapter;

import sk.naive.talker.util.Utils;

import java.util.*;

/**
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.5 $ $Date: 2004/10/13 21:14:41 $
 */
public class StyleSheet {
	private static final Map ansiMap;

	private static final Map sheetsMap;

	private Map styleMap;

	private StyleSheet(String sheetName) {
		styleMap = new HashMap();

		ResourceBundle rb = ResourceBundle.getBundle("sk/naive/talker/tcpadapter/styleSheet-" + sheetName);
		for (Enumeration e = rb.getKeys(); e.hasMoreElements(); ) {
			String styleClassName = (String) e.nextElement();
			String pseudoAnsi = rb.getString(styleClassName);
			styleMap.put(styleClassName, ansiSequence(pseudoAnsi));
		}
		sheetsMap.put(sheetName, this);
	}

	public static StyleSheet getStyleSheet(String sheetName) {
		StyleSheet ss = (StyleSheet) sheetsMap.get(sheetName);
		if (ss != null) {
			return ss;
		}
		return new StyleSheet(sheetName);
	}

	public String getAnsiSequence(String styleClass) {
		return (String) styleMap.get(styleClass);
	}

	private String ansiSequence(String pseudoAnsi) {
		if (pseudoAnsi == null || pseudoAnsi.length() == 0) {
			return "";
		}
		String[] sa = Utils.split(pseudoAnsi, ",", -1);
		StringBuilder sb = new StringBuilder("\033[");
		for (int i = 0; i < sa.length; i++) {
			String ansiCode = (String) ansiMap.get(sa[i].toLowerCase());
			if (ansiCode == null) {
				Utils.warning("Invalid style code " + sa[i]);
			}
			if (i > 0) {
				sb.append(";");
			}
			sb.append(ansiCode);
		}
		return sb.append("m").toString();
	}

	static {
		sheetsMap = new HashMap();

		ansiMap = new HashMap();
		ansiMap.put("off", "0");
		ansiMap.put("bold", "1");
		ansiMap.put("underscore", "4");
		ansiMap.put("blink", "5");
		ansiMap.put("reverse", "7");
		ansiMap.put("concealed", "8");
		ansiMap.put("fblack", "30");
		ansiMap.put("fred", "31");
		ansiMap.put("fgreen", "32");
		ansiMap.put("fyellow", "33");
		ansiMap.put("fblue", "34");
		ansiMap.put("fmagenta", "35");
		ansiMap.put("fcyan", "36");
		ansiMap.put("fwhite", "37");
		ansiMap.put("black", "30");
		ansiMap.put("red", "31");
		ansiMap.put("green", "32");
		ansiMap.put("yellow", "33");
		ansiMap.put("blue", "34");
		ansiMap.put("magenta", "35");
		ansiMap.put("cyan", "36");
		ansiMap.put("white", "37");
		ansiMap.put("bblack", "40");
		ansiMap.put("bred", "41");
		ansiMap.put("bgreen", "42");
		ansiMap.put("byellow", "43");
		ansiMap.put("bblue", "44");
		ansiMap.put("bmagenta", "45");
		ansiMap.put("bcyan", "46");
		ansiMap.put("bwhite", "47");
		ansiMap.put("bgblack", "40");
		ansiMap.put("bgred", "41");
		ansiMap.put("bggreen", "42");
		ansiMap.put("bgyellow", "43");
		ansiMap.put("bgblue", "44");
		ansiMap.put("bgmagenta", "45");
		ansiMap.put("bgcyan", "46");
		ansiMap.put("bgwhite", "47");
	}
}
